from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException
from starlette import status
from sqlalchemy.orm import Session
import models
from models.db import get_db
from schemas import response_success, response_error
from schemas.user import ChangePasswordSchema, UserCreate, UserProfile
from fastapi.security import OAuth2PasswordRequestForm
from views.auth import create_access_token, get_password_hash, oauth2_scheme, get_current_user_id, \
    verify_password

login_router = APIRouter()
router = login_router

ACCESS_TOKEN_EXPIRE_MINUTES = 720


@router.post("/register")
async def register_user(user: UserCreate, db: Session = Depends(get_db)):
    """注册用户"""
    if user.password.strip() != user.confirmPassword.strip():
        return response_error('两次密码输入不一致')
    if user.code != '9017':
        return response_error('注册码不匹配')

    db_user = db.query(models.User).filter(models.User.username == user.username).first()
    if db_user:
        return response_error('用户已存在')

    fake_hashed_password = get_password_hash(user.password.strip())
    db_user = models.User(username=user.username, hashed_password=fake_hashed_password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)

    return response_success('注册成功')


@router.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    db_user = db.query(models.User).filter(models.User.username == form_data.username).first()
    if db_user:
        if verify_password(form_data.password, db_user.hashed_password):
            access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
            access_token = create_access_token(
                data={"sub": db_user.username, 'id': str(db_user.id)}, expires_delta=access_token_expires
            )
            return {"access_token": access_token, "token_type": "bearer", 'code': 0}

    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="用户认证失败",
        headers={"WWW-Authenticate": "Bearer"},
    )


@router.post("/logout")
async def logout(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
    blacklist = models.Blacklist(token=token)
    db.add(blacklist)
    db.commit()
    return response_success('注销成功')


@router.get("/current-user")
async def current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
    user_id = get_current_user_id(token)
    db_user = db.query(models.User).filter(models.User.id == user_id).first()
    if not db_user:
        return response_error('获取用户信息错误，用户不存在！')

    user_info = {
        'username': db_user.username,
        'avatar': db_user.avatar,
        'theme': db_user.theme,
    }
    return response_success(data=user_info)


@router.post("/update-profile")
async def profile(form: UserProfile, token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
    user_id = get_current_user_id(token)
    db_user = db.query(models.User).filter(models.User.id == user_id).first()
    if not db_user:
        return response_error('获取用户信息错误，用户不存在！')
    for k, v in form.dict().items():
        # print(k, v, getattr(db_user, k))
        # if getattr(db_user, k):
        #     print('sdf')
        setattr(db_user, k, v)

    db.commit()
    return response_success()


@router.put("/change-password")
async def change_password(form: ChangePasswordSchema, token: str = Depends(oauth2_scheme),
                          db: Session = Depends(get_db)):
    """用户修改密码"""
    user_id = get_current_user_id(token)
    db_user = db.query(models.User).filter_by(id=user_id).first()
    if not db_user:
        response_error('获取用户信息错误，用户不存在！')

    if form.newPassword != form.confirmPassword:
        return response_error('确认密码输入不一致！')

    if not verify_password(form.oriPassword, db_user.hashed_password):
        return response_error('密码验证失败！')

    db_user.hashed_password = get_password_hash(form.newPassword)
    db.commit()

    return response_success('密码修改成功')
